<?php

namespace app\api\library;


use think\Db;

/**
 * 商城接口
 */
class Shop
{
    // 商家信息
    public function shop_info($field = '*',$where = []){

        return Db::table('fa_shop s')
            ->field($field)
            ->join('fa_user u','u.id = s.user_id')
            ->where($where)
            ->find();
    }


    // 商品详情
    public function goods_info($id,$all = 0){
        $where = [
            'g.id' => $id
        ];
        if($all == 0){
            $where['g.status'] = 1;
        }
        return Db::table('fa_goods g')
            ->field('g.*,s.name as shop_name')
            ->join('fa_shop s','s.id = g.shop_id')
            ->join('fa_user u','u.id = s.user_id')
            ->where($where)
            ->where('u.shop_expire_time','>',time())
            ->order('topping desc,updatetime desc')
            ->find();
    }

    // 商品列表
    public function goods_list($where,$keyword,$size){
        return  Db::table('fa_goods g')
            ->field('g.*,s.name as shop_name,s.image as shop_image')
            ->join('fa_shop s','s.id = g.shop_id')
            ->join('fa_user u','u.id = s.user_id')
            ->where($where)
            ->where(function($query) use ($keyword){
                if($keyword){
                    $query->where('s.name','like',"%{$keyword}%")
                        ->whereOr('g.name','like',"%{$keyword}%")
                        ->whereOr('g.content','like',"%{$keyword}%");
                }
            })
            ->where('u.shop_expire_time','>',time())
            ->where('u.freeze',0)
            ->order('topping desc,updatetime desc')
            ->paginate($size)
            ->each(function($item){

                $item['shop_image'] = completion_image($item['shop_image']);

                $item['image'] = completion_image($item['image']);
                $item['images'] = completion_image($item['images'],1);
                return $item;
            });
    }



    //  需求列表

    public function demand_list($where,$size){
        return Db::table('fa_demand d')
            ->field('d.*,u.nickname,u.avatar')
            ->join('fa_user u','u.id = d.user_id')
            ->where($where)
            ->order('d.id desc')
            ->paginate($size)
            ->each(function($item){
                $item['images'] = completion_image($item['images'],1);
                return $item;
            });

    }

    // 需求详情
    public function demand_info($where){
        $info = Db::table('fa_demand d')
            ->field('d.*,u.nickname,u.avatar')
            ->join('fa_user u','u.id = d.user_id')
            ->where($where)
            ->find();
        if(empty($info)){
            return [];
        }

        $info['images'] = completion_image($info['images'],1);
        return $info;
    }
}
